#include "bsp_tim3.h"

TIM_HandleTypeDef htim3;
TIM_OC_InitTypeDef sConfigOC;
TIM_ClockConfigTypeDef sClockSourceConfig;
TIM_MasterConfigTypeDef sMasterConfig;

/*
*Ft：定时器工作频率,单位:Mhz
*arr：自动重装值。 psc：时钟预分频数  
*定时器溢出时间计算方法:Tout = ((arr+1)*(psc+1))/Ft us.
*20000 * 84 / 84 = 20000us   
*PWM周期20ms
*/
void MX_TIM3_Init(void)
{
    __HAL_RCC_TIM3_CLK_ENABLE();
    htim3.Instance = TIM3;
    htim3.Init.Prescaler = 84-1;                 //定时器分频系数
    htim3.Init.CounterMode = TIM_COUNTERMODE_UP; //向上计数
    htim3.Init.Period = 20000-1;                 //自动重装载值
    htim3.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
    htim3.Init.RepetitionCounter = 0;
    HAL_TIM_Base_Init(&htim3);

    sClockSourceConfig.ClockSource = TIM_CLOCKSOURCE_INTERNAL;
    HAL_TIM_ConfigClockSource(&htim3, &sClockSourceConfig);

    if (HAL_TIM_PWM_Init(&htim3) != HAL_OK)
    {
        _Error_Handler(__FILE__, __LINE__);
    }

   // HAL_TIM_OC_Init(&htim3);
    sMasterConfig.MasterOutputTrigger = TIM_TRGO_OC1;
    sMasterConfig.MasterSlaveMode     = TIM_MASTERSLAVEMODE_DISABLE;
    if (HAL_TIMEx_MasterConfigSynchronization(&htim3, &sMasterConfig) != HAL_OK)
    {
        _Error_Handler(__FILE__, __LINE__);
    }

    sConfigOC.OCMode       = TIM_OCMODE_PWM1;
    sConfigOC.Pulse        = 800;                 //脉宽  单位：us
    sConfigOC.OCPolarity   = TIM_OCPOLARITY_HIGH;
    sConfigOC.OCFastMode   = TIM_OCFAST_DISABLE;
    sConfigOC.OCIdleState  = TIM_OCIDLESTATE_RESET;
    sConfigOC.OCNIdleState = TIM_OCNIDLESTATE_RESET;
    HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_1);
    HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_2);

    HAL_TIM_PWM_MspInit(&htim3);

    HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_1);//开启PWM通道1
    HAL_TIM_PWM_Start(&htim3,TIM_CHANNEL_2);//开启PWM通道2         
}

void HAL_TIM_PWM_MspInit(TIM_HandleTypeDef *htim)
{
    if(htim->Instance == TIM3)
    {
        GPIO_InitTypeDef GPIO_InitStruct;

        __HAL_RCC_TIM3_CLK_ENABLE();

        PWM1_PORT_CLK_ENABLE();
        PWM2_PORT_CLK_ENABLE();

        GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
        GPIO_InitStruct.Pull = GPIO_PULLUP;
        GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
        GPIO_InitStruct.Alternate = GPIO_AF2_TIM3;

        GPIO_InitStruct.Pin = PWM1_PIN;
        HAL_GPIO_Init(PWM1_PORT, &GPIO_InitStruct);
        GPIO_InitStruct.Pin = PWM2_PIN;
        HAL_GPIO_Init(PWM2_PORT, &GPIO_InitStruct);
    }
}

void PWM1_Setus(uint32_t us)
{
    sConfigOC.Pulse = us;

    if (HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
    {
        
    }

    if (HAL_TIM_PWM_Start_IT(&htim3, TIM_CHANNEL_1) != HAL_OK)
    {
       
    }        
}

void PWM2_Setus(uint32_t us)
{
    sConfigOC.Pulse = us;
    
    if (HAL_TIM_PWM_ConfigChannel(&htim3, &sConfigOC, TIM_CHANNEL_2) != HAL_OK)
    {
       
    }
    
    if (HAL_TIM_PWM_Start_IT(&htim3, TIM_CHANNEL_2) != HAL_OK)
    {
        
    }
}


